
# coding:utf-8

from lib import flux, al, pymunk
from lib.fluxext import ViewGroup
from system.map import MapManager
from views.bullet import EnemyBullet
from scripts.base import config
from system import phy
from utils import dir2vec
from views.unit import Unit


class Enemy(Unit):
    def __init__(self, spd=75, force=2000, last_dir=None):
        super(Enemy, self).__init__(spd, force, (40, 40), last_dir)

        self.bullet_type = EnemyBullet

        sprite = flux.View()
        sprite.SetAnchor(self.anchor)
        sprite.SetSize(36,36)
        sprite.SetColor(1,1,0)

        self.sprite = sprite

        from system.AI import AISys
        AISys().AddEnemy(self)

    def GetSize(self):
        return self.sprite.GetSize()

    def ApplyPhy(self):
        pos = self.anchor.GetPos()
        size = self.sprite.GetSize()
        body = pymunk.Body(1, pymunk.inf)

        body.position = pymunk.vec2d.Vec2d(pos.x, pos.y)
        body.velocity_limit = self.attr.spd

        poly = pymunk.Poly.create_box(body, (size.x, size.y))
        poly.group = phy.GROUP_ENEMY
        poly.layers = pow(2, 2) | pow(2, 3)
        phy.space.add(body, poly)

        self.body = body
        phy.Reg(body, self)

    def Dead(self):
        super(Enemy, self).Dead()
        from system.AI import AISys
        AISys().RmEnemy(self)
        phy.Remove(self.body)
        for k,v in self:
            vars(self)[k] = None
        self.attr = None
